package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.cp.api.entity.sync.SyncFinaExpireInfoEntity;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.enums.sync.CrmServiceEnum;
import com.pactera.madp.cp.common.util.sync.SyncUtils;
import com.pactera.madp.cp.config.SyncConfig;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.mapper.sync.SyncFinaExpireInfoMapper;
import com.pactera.madp.cp.service.sync.SyncFinaExpireInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class SyncFinaExpireInfoServiceImpl extends ServiceImpl<SyncFinaExpireInfoMapper, SyncFinaExpireInfoEntity> implements SyncFinaExpireInfoService {

    private final SyncConfig syncConfig;

    @Override
    public void addYesterdayToHis() {

    }

    @Override
    public void deleteYesterday() {
        log.debug("理财信息：deleteBeforeOneWeek");
        // 只保留7天后到期的数据
        Date dateTime = new Date();
        String fileDate = SyncStateContext.get().getFileDate();
        if (StrUtil.isNotEmpty(fileDate)) {
            dateTime = DateUtil.parse(fileDate, Constants.DATE_FORMAT);
        }
        String date = DateUtil.format(dateTime, Constants.DATE_FORMAT);

        this.remove(Wrappers.<SyncFinaExpireInfoEntity>lambdaQuery()
                .lt(SyncFinaExpireInfoEntity::getExpireDt, date));
    }

    @Override
    public void parse() {
        log.debug("理财信息：check");
        String fileDate = SyncStateContext.get().getFileDate();
        if (!checkFile(fileDate)) {
            log.error("{}{}", CrmServiceEnum.FINA_EXPIRE.getSubType(), "同步文件未生成完毕");
            return;
        }
        log.debug("理财信息：parse");
        String filepath = SyncUtils.buildFilePath(syncConfig.getCrmPath(), Constants.FN_FINA_EXPIRE, fileDate);
        File newestFile = SyncUtils.getNewestFile(filepath);

        List<SyncFinaExpireInfoEntity> entityList
                = SyncUtils.parse(newestFile, Constants.SEPARATOR_VERTICAL_LINE, SyncFinaExpireInfoEntity.class, syncConfig.getCrmCharset());

        this.saveBatch(entityList);
    }

    @Override
    public void deleteHisOneDay() {

    }

    @Override
    public void syncBusiness() {
        log.debug("理财信息：syncBusiness");
        SyncStateContext.get().setFinalState(true);
    }

    private boolean checkFile(String fileDate) {
        String filepath = SyncUtils.buildFilePath(syncConfig.getCrmPath(), Constants.FN_FINA_EXPIRE_OK, fileDate);
        return SyncUtils.checkFile(filepath);
    }

}
